const express = require('express');
const router = express.Router();
const { 
  storePositionData, 
  queryPositions,
  deletePositionData
} = require('../db/positionStorage');

// 存储职位数据到数据库
router.get('/store', async (req, res) => {
  try {
    const { province, city, date } = req.query;
    
    if (!province || !city || !date) {
      return res.status(400).json({ 
        error: '必须提供所有参数: province, city, date'
      });
    }
    
    const result = await storePositionData(province, city, date);
    res.json(result);
  } catch (error) {
    console.error('存储职位数据时出错:', error);
    res.status(500).json({ error: error.message });
  }
});

// 查询职位数据
router.get('/query', async (req, res) => {
  try {
    const { province, city, date, ...filters } = req.query;
    
    if (!province || !city || !date) {
      return res.status(400).json({ 
        error: '必须提供所有参数: province, city, date'
      });
    }
    
    const result = await queryPositions(province, city, date, filters);
    res.json(result);
  } catch (error) {
    console.error('查询职位数据时出错:', error);
    res.status(500).json({ error: error.message });
  }
});

// 删除职位数据
router.delete('/delete', async (req, res) => {
  try {
    const { province, city, date, positionCode } = req.query;
    
    if (!province || !city || !date) {
      return res.status(400).json({ 
        error: '必须提供所有参数: province, city, date'
      });
    }
    
    const result = await deletePositionData(province, city, date, positionCode);
    res.json(result);
  } catch (error) {
    console.error('删除职位数据时出错:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;